package com.bs.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.bs.dao.BaseDao;
import com.bs.dao.CategoryDao;
import com.bs.entity.MedicineCategory;
import com.bs.entity.MedicineInfo;

/**
 * 药品类别dao层处理类
 * 
 * @author Shimeimei
 * 
 */
public class CategoryDaoImpl extends BaseDao implements CategoryDao {

	/**
	 * 新增药品类别
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addCategory(MedicineCategory medicineCategory) {
		boolean flag = false;
		try {
			hibernateTemplate.save(medicineCategory);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 获取药品类别列表
	 */
	public List<MedicineCategory> getCategoryList() {
		String hql = "from MedicineCategory";
		List<MedicineCategory> list = null;
		try {
			list = hibernateTemplate.find(hql);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	/**
	 * 更新药品类别
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateCategory(MedicineCategory medicineCategory) {
		boolean flag = false;
		try {
			hibernateTemplate.update(medicineCategory);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 获取类别的详细信息
	 */
	public MedicineCategory getMedicineCategory(String id) {
		String hql = "from MedicineCategory c left join fetch c.medicineInfos where c.categoryId=?";
		MedicineCategory category = null;
		try {
			category = (MedicineCategory) hibernateTemplate.find(hql,
					new Object[] { Long.parseLong(id) }).get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return category;
	}
  
	/**
	 * 刪除药品类别信息
	 */
	public boolean deleteCategory(MedicineCategory medicineCategory) {
        boolean flag =false;
        try {
        	 //解除级联关系
        	  medicineCategory.setMedicineInfos(null);
        	 if(medicineCategory.getMedicineInfos()!=null){
        	    Set<MedicineCategory> set =medicineCategory.getMedicineInfos();
        	    for(Iterator it =set.iterator();it.hasNext();){
        	    	MedicineInfo me =(MedicineInfo)it.next();
        	        me.setMedicineCategory(null);
        	    	
        	    }
        	 }
        	 
			hibernateTemplate.delete(medicineCategory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
}

